from sly import Parser
from minorlex import MinorLexer

class MinorParser(Parser):
    # Get the token list from the lexer (required) tokens = CalcLexer.tokens
    # Grammar rules and actions 

    # precedence

    @_('expr PLUS term') 
    def expr(self, p): 
        return p.expr + p.term

    @_('expr MINUS term')
    def expr(self, p):
        return p.expr - p.term

    @_('term') 
    def expr(self, p):
        return p.term

    @_('term TIMES factor')
    def term(self, p):
        return p.term * p.factor

    @_('term DIVIDE factor') 
    def term(self, p):
        return p.term / p.factor

    @_('factor') 
    def term(self, p):
        return p.factor

    @_('expr QE term')
    def term(self, p):
        if p.expr == p.term True else False

    @_('NUMBER')
    def factor(self, p): 
        return p.NUMBER
    
    @_('BOOL')
    def _bool(self, p):
        return p.BOOL

    @_('LPAREN expr RPAREN') 
    def factor(self, p): 
       return p.expr

    @_("IF'('expr')''{'term'}'")
    def _if(self, p):
        if p.expr == True:
            return p.term
        else:
            return None
       
if __name__ == '__main__': 
    lexer = MinorLexer() 
    parser = MinorParser()
    while True:
        try:
            text = input('calc > ')
            result = parser.parse(lexer.tokenize(text))
            print(result)
        except EOFError:
            break
